<template>
  <div class="mr-2 overflow-hidden bg-white h-full">
    <BasicTree
      :title="t('组织列表')"
      toolbar
      search
      :clickRowToExpand="true"
      :treeData="treeData"
      :selectedKeys="selectedKeys"
      expandOnSearch
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    >
      <template #title="{ name, departmentType }">
        <a-tag color="processing" v-if="departmentType === 1">公司</a-tag>
        <a-tag color="warning" v-else-if="departmentType === 0">部门</a-tag>
        {{ name }}
      </template>
    </BasicTree>
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { getDepartmentTree } from '/@/api/system/department';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      const selectedKeys = ref<string[]>([]);

      async function fetch() {
        treeData.value = (await getDepartmentTree()) as unknown as TreeItem[];
        let id = treeData.value[0].id;
        selectedKeys.value.push(id);
        emit('select', id);
      }

      function handleSelect(keys: string) {
        emit('select', keys[0]);
      }

      onMounted(() => {
        fetch();
      });
      return { treeData, handleSelect, selectedKeys, t };
    },
  });
</script>
